package com.mdnote.practice.plus_search.prune;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Rhythm-2019
 * @date 2020/10/4
 * @description 有效的数独
 */
public class LeetCode36 {
    public boolean isValidSudoku(char[][] board) {

        // 只需要一次遍历就可以判断是否合法了
        Set<Integer>[] rows = new HashSet[9];
        Set<Integer>[] columns = new HashSet[9];
        Set<Integer>[] blocks = new HashSet[9];
//        对于引用类型千万不要使用这个方法填充
//        Arrays.fill(rows, new HashSet<Integer>());
//        Arrays.fill(columns, new HashSet<Integer>());
//        Arrays.fill(blocks, new HashSet<Integer>());
        for (int i = 0; i < 9; i++) {
            rows[i] = new HashSet<>();
            columns[i] = new HashSet<>();
            blocks[i] = new HashSet<>();
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == '.') {
                    continue;
                }
                int num = board[i][j] - '0';
                int block_index = (i / 3) * 3 + j / 3;
                if (rows[i].contains(num) || columns[j].contains(num) || blocks[block_index].contains(num)) {
                    return false;
                }
                rows[i].add(num);
                columns[j].add(num);
                blocks[block_index].add(num);
            }
        }
        return true;
    }


}
